<template>
  <div class="map-container">
    <!-- 地图容器，占满整个宽度和高度 -->
    <div id="map" style="width: 100vw; height: 100vh"></div>
    
    <!-- 地图加载提示，2秒后自动隐藏 -->
    <div v-if="!mapInitialized" class="map-loading">
      <div class="loading-spinner"></div>
      <div class="loading-text">地图加载中...</div>
    </div>
    
    <!-- 地理标记，带有动画的图片 -->
    <div id="geo-marker" class="css_animation">
      <img :src="myplanImg" style="width: 3vw" />
    </div>
    
    <!-- 用于显示速度的测量提示 -->
    <div class="measuretip" id="speed"></div>

    <!-- 整合地图控制按钮部分 -->
    <div class="map-controls" v-if="mapInitialized">
      <div class="control-section">
        <div class="control-item">
          <el-button @click="toggleView" :type="currentIs2D ? 'default' : 'primary'">
            {{ currentIs2D ? '切换到3D' : '切换到2D' }}
          </el-button>
        </div>
        
        <div class="control-item">
          <el-button @click="resetView">
            重置视图
          </el-button>
        </div>
      </div>
      
      <!-- 3D模式下显示键盘控制提示 -->
      <div class="keyboard-tips" v-if="!currentIs2D && showKeyboardTips">
        <div class="tips-title">键盘控制 <el-icon class="close-icon" @click="showKeyboardTips = false"><Close /></el-icon></div>
        <div class="tips-content">
          <p>↑↓ - 前进/后退</p>
          <p>←→ - 左右旋转</p>
          <p>PageUp/PageDown - 上升/下降</p>
        </div>
      </div>
    </div>
    
    <!-- 子组件插槽 -->
    <slot></slot>
  </div>
</template>

<script setup>
import { ref, computed, provide, onMounted, onBeforeUnmount, reactive, watch, nextTick, onUnmounted } from 'vue';
import { useMapControl } from '@/hooks/useMapControl';
import { ElMessage } from 'element-plus';
import { Close } from '@element-plus/icons-vue';
import { useMapStore } from '@/stores/modules/map'
import { useToolsStore } from '@/stores/modules/tools'

// 定义组件可以发出的事件
const emit = defineEmits(['map-ready']);

// 地图控制钩子
const { 
  map, 
  map3d, 
  is2D, 
  sourceFeatures, 
  lineString,
  initMap, 
  init3DMap, 
  toggleDimension,
  cleanup
} = useMapControl();

const mapStore = useMapStore()
const toolsStore = useToolsStore()

// 使用store中的状态
const mapInitialized = computed(() => mapStore.mapInitialized)
const currentIs2D = computed(() => !mapStore.is3DMode)
const isRotating = computed(() => mapStore.isRotating)
const showKeyboardTips = computed(() => mapStore.showKeyboardTips)
const keyState = computed(() => mapStore.keyState)
const movementSpeed = computed(() => mapStore.movementSpeed)
const rotationSpeed = computed(() => mapStore.rotationSpeed)

// 动画图标
const myplanImg = ref('/icons/icon-right.gif');

// 默认中心点
const defaultCenter = [121.62021584789193, 29.9239055235632];
const defaultZoom = 15;

// 相机旋转状态
const rotationAnimation = ref(null);

// 暴露给父组件的方法
defineExpose({
  getMap: () => map.value,
  getMap3d: () => map3d.value,
  getIs2D: () => is2D.value,
  getSourceFeatures: () => sourceFeatures.value,
  getLineString: () => lineString.value,
  toggleDimension,
  isInitialized: () => mapInitialized.value
});

/**
 * 包装切换视图函数，确保界面状态更新
 */
function toggleView() {
  console.log('切换视图前状态:', is2D.value);
  const newState = toggleDimension();
  console.log('切换视图后状态:', newState);
  mapStore.toggleView();
  
  // 切换到3D视图时添加相机动画效果
  if (!newState) {
    nextTick(() => {
      // 使用默认参数设置相机位置
      if (map3d.value) {
        const scene = map3d.value.getCesiumScene();
        const camera = scene.camera;
        const Cesium = window.Cesium;
        
        if (Cesium) {
          // 使用默认中心点
          const defaultCenter = Cesium.Cartographic.fromDegrees(
            121.62021584789193,
            29.9239055235632,
            0
          );
          const center = Cesium.Cartesian3.fromRadians(
            defaultCenter.longitude,
            defaultCenter.latitude,
            defaultCenter.height
          );
          
          // 设置相机位置和朝向
          camera.lookAt(
            center,
            new Cesium.HeadingPitchRange(
              0, // heading
              Cesium.Math.toRadians(-45), // pitch
              500 // radius
            )
          );
        }
      }
    });
  }
}

/**
 * 重置视图到默认位置 - 从MapControls组件整合
 */
function resetView() {
  if (!map.value) return;
  
  map.value.getView().animate({
    center: defaultCenter,
    zoom: defaultZoom,
    duration: 1000
  });
}

/**
 * 修复3D模式下的点击事件
 * 确保绘图和测量工具能正常接收点击事件
 */
function fixCesiumClickEvents() {
  try {
    console.log('修复3D模式下的事件穿透问题');
    // 获取Cesium场景和画布
    const cesiumEl = document.querySelector('.cesium-widget');
    if (!cesiumEl) {
      console.warn('未找到Cesium元素，跳过事件穿透修复');
      return;
    }
    
    const cesiumCanvas = document.querySelector('.cesium-widget canvas');
    if (!cesiumCanvas) {
      console.warn('未找到Cesium Canvas，跳过事件穿透修复');
      return;
    }
    
    // 添加特殊样式，确保事件穿透
    if (!document.getElementById('cesium-event-fix-style')) {
      const style = document.createElement('style');
      style.id = 'cesium-event-fix-style';
      style.innerHTML = `
        .cesium-widget {
          pointer-events: none !important;
        }
        .cesium-widget canvas {
          pointer-events: none !important;
        }
        .ol-viewport {
          z-index: 1000 !important;
          pointer-events: auto !important;
        }
        .draw-tools, .measure-tools {
          z-index: 2000 !important;
          pointer-events: auto !important;
        }
        .measure-tooltip {
          z-index: 2001 !important;
          pointer-events: auto !important;
        }
        .ol-unselectable {
          pointer-events: auto !important;
        }
      `;
      document.head.appendChild(style);
      console.log('已添加3D模式事件穿透修复样式');
    }
    
    // 修改Cesium元素样式 - 禁用鼠标事件
    cesiumEl.style.pointerEvents = 'none';
    cesiumCanvas.style.pointerEvents = 'none';
    
    // 确保OpenLayers视口和工具条可以接收事件
    const olViewport = document.querySelector('.ol-viewport');
    if (olViewport) {
      olViewport.style.zIndex = '1000';
      olViewport.style.pointerEvents = 'auto';
    }
    
    // 查找并修复工具栏元素
    const toolContainers = document.querySelectorAll('.draw-tools, .measure-tools');
    toolContainers.forEach(container => {
      if (container) {
        container.style.zIndex = '2000';
        container.style.pointerEvents = 'auto';
        
        // 修复按钮事件
        const buttons = container.querySelectorAll('button');
        buttons.forEach(button => {
          button.style.zIndex = '2001';
          button.style.pointerEvents = 'auto';
          button.style.position = 'relative';
        });
      }
    });
    
    // 禁用Cesium的默认鼠标控制
    if (map3d.value) {
      const scene = map3d.value.getCesiumScene();
      if (scene && scene.screenSpaceCameraController) {
        scene.screenSpaceCameraController.enableRotate = false;
        scene.screenSpaceCameraController.enableTranslate = false;
        scene.screenSpaceCameraController.enableZoom = false;
        scene.screenSpaceCameraController.enableTilt = false;
        scene.screenSpaceCameraController.enableLook = false;
        console.log('已禁用Cesium默认鼠标控制');
      }
    }
    
    console.log('3D模式事件穿透问题修复完成');
  } catch (error) {
    console.error('修复3D模式事件穿透失败:', error);
  }
}

/**
 * 设置键盘事件监听
 */
function setupKeyboardControls() {
  console.log('设置键盘控制...');
  
  // 键盘按下
  const handleKeyDown = (event) => {
    console.log('键盘按下:', event.key);
    if (is2D.value) {
      console.log('2D模式下不处理键盘控制');
      return;
    }
    
    switch (event.key) {
      case 'ArrowUp':
        console.log('前进');
        mapStore.setKeyState('forward', true);
        break;
      case 'ArrowDown':
        console.log('后退');
        mapStore.setKeyState('backward', true);
        break;
      case 'ArrowLeft':
        console.log('左转');
        mapStore.setKeyState('left', true);
        break;
      case 'ArrowRight':
        console.log('右转');
        mapStore.setKeyState('right', true);
        break;
      case 'PageUp':
        console.log('上升');
        mapStore.setKeyState('up', true);
        break;
      case 'PageDown':
        console.log('下降');
        mapStore.setKeyState('down', true);
        break;
    }
  };
  
  // 键盘释放
  const handleKeyUp = (event) => {
    console.log('键盘释放:', event.key);
    switch (event.key) {
      case 'ArrowUp':
        mapStore.setKeyState('forward', false);
        break;
      case 'ArrowDown':
        mapStore.setKeyState('backward', false);
        break;
      case 'ArrowLeft':
        mapStore.setKeyState('left', false);
        break;
      case 'ArrowRight':
        mapStore.setKeyState('right', false);
        break;
      case 'PageUp':
        mapStore.setKeyState('up', false);
        break;
      case 'PageDown':
        mapStore.setKeyState('down', false);
        break;
    }
  };
  
  // 添加事件监听
  window.addEventListener('keydown', handleKeyDown);
  window.addEventListener('keyup', handleKeyUp);
  
  // 设置相机移动循环
  let cameraControlLoop = null;
  
  function updateCamera() {
    if (is2D.value || !map3d.value) {
      return;
    }
    
    const scene = map3d.value.getCesiumScene();
    const camera = scene.camera;
    
    // 检查键盘状态并移动相机
    if (keyState.value.forward) {
      console.log('相机前进');
      camera.moveForward(movementSpeed.value);
    }
    if (keyState.value.backward) {
      console.log('相机后退');
      camera.moveBackward(movementSpeed.value);
    }
    if (keyState.value.left) {
      console.log('相机左转');
      camera.lookLeft(rotationSpeed.value);
    }
    if (keyState.value.right) {
      console.log('相机右转');
      camera.lookRight(rotationSpeed.value);
    }
    if (keyState.value.up) {
      console.log('相机上升');
      camera.moveUp(movementSpeed.value);
    }
    if (keyState.value.down) {
      console.log('相机下降');
      camera.moveDown(movementSpeed.value);
    }
    
    // 继续循环
    cameraControlLoop = requestAnimationFrame(updateCamera);
  }
  
  // 启动相机控制循环
  cameraControlLoop = requestAnimationFrame(updateCamera);
  console.log('相机控制循环已启动');
  
  // 返回清理函数
  return () => {
    console.log('清理键盘控制...');
    window.removeEventListener('keydown', handleKeyDown);
    window.removeEventListener('keyup', handleKeyUp);
    if (cameraControlLoop) {
      cancelAnimationFrame(cameraControlLoop);
      cameraControlLoop = null;
    }
  };
}

// 监听地图模式变化
watch(() => mapStore.is3DMode, (newMode) => {
  console.log('地图模式变化:', newMode ? '3D' : '2D');
  if (newMode) {
    // 切换到3D模式时，初始化3D地图
    init3DMap();
  }
});

// 监听旋转状态变化
watch(() => mapStore.isRotating, (newStatus) => {
  console.log('旋转状态变化:', newStatus);
  if (!newStatus && rotationAnimation.value) {
    cancelAnimationFrame(rotationAnimation.value);
    rotationAnimation.value = null;
  }
});

// 初始化地图
onMounted(async () => {
  try {
    console.log('开始地图初始化过程...');
    
    // 初始化重试机制
    let retryCount = 0;
    const maxRetries = 3;
    let initSuccess = false;
    
    // 重试初始化函数
    const tryInitMap = async () => {
      try {
        // 初始化2D地图
        const mapInstance = initMap('map');
        
        if (!mapInstance) {
          console.warn(`地图初始化失败，尝试 #${retryCount+1}`);
          return false;
        }
        
        // 初始化3D地图
        init3DMap();
        
        // 更新store中的状态
        mapStore.setMapInstance(map.value);
        mapStore.setMap3DInstance(map3d.value);
        mapStore.setSourceFeatures(sourceFeatures.value);
        mapStore.setLineString(lineString.value);
        
        // 设置键盘控制
        const cleanupKeyboard = setupKeyboardControls();
        
        // 在组件卸载时清理键盘控制
        onBeforeUnmount(() => {
          cleanupKeyboard();
        });
        
        return true;
      } catch (err) {
        console.error(`地图初始化尝试 #${retryCount+1} 失败:`, err);
        return false;
      }
    };
    
    // 尝试初始化，最多重试几次
    while (!initSuccess && retryCount < maxRetries) {
      initSuccess = await tryInitMap();
      if (!initSuccess) {
        retryCount++;
        // 等待一段时间再重试
        if (retryCount < maxRetries) {
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
    }
    
    // 显示初始化后的对象状态
    console.log('初始化完成后的对象状态:', {
      'map引用': map,
      'map.value': map.value,
      'sourceFeatures引用': sourceFeatures,
      'sourceFeatures.value': sourceFeatures.value
    });
    
    // 提供给子组件的上下文 - 无论初始化是否成功都执行
    provide('mapContext', reactive({
      map,
      map3d,
      is2D,
      sourceFeatures,
      lineString
    }));
    
    // 为了兼容现有代码，同时提供单独的注入
    provide('map', map);
    provide('map3d', map3d);
    provide('is2D', is2D);
    provide('sourceFeatures', sourceFeatures);
    provide('lineString', lineString);
    provide('mapContainerRef', ref(this));
    
    // 监听is2D变化以显示提示信息 - 从MapControls组件整合
    watch(is2D, (newValue) => {
      ElMessage({
        message: `已切换到${newValue ? '2D' : '3D'}视图`,
        type: 'success',
        duration: 1500
      });
      
      // 切换到3D模式时，修复点击事件穿透问题
      if (!newValue) { // 3D模式
        nextTick(() => {
          fixCesiumClickEvents();
          // 重新设置键盘控制
          const cleanupKeyboard = setupKeyboardControls();
          onBeforeUnmount(() => {
            cleanupKeyboard();
          });
        });
      }
    });
    
    // 强制设置初始化完成
    mapStore.setMapInitialized(true);
    console.log(`地图初始化${initSuccess ? '成功' : '失败，但已完成流程'}`);
    
    // 向父组件发送地图就绪事件
    emit('map-ready', {
      map: map.value,
      map3d: map3d.value,
      is2D: is2D.value,
      sourceFeatures: sourceFeatures.value,
      lineString: lineString.value,
      initSuccess: initSuccess
    });
    
    // 添加地图渲染完成事件监听 - 仅在地图对象存在时添加
    if (map.value) {
      try {
        map.value.once('rendercomplete', function() {
          console.log('地图渲染完成事件触发');
        });
      } catch (e) {
        console.error('添加渲染事件监听器失败:', e);
      }
    }
  } catch (error) {
    console.error('地图初始化过程出错:', error);
    mapStore.setMapInitialized(true);
    
    // 向父组件发送初始化失败事件
    emit('map-ready', {
      map: null,
      map3d: null,
      is2D: true,
      sourceFeatures: null,
      lineString: null,
      initSuccess: false,
      error: error.message
    });
  }
});

// 组件卸载时清理
onBeforeUnmount(() => {
  cleanup();
});

// 在组件卸载时清理
onUnmounted(() => {
  // 清理逻辑...
});
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.measuretip {
  position: relative;
  background-color: #f4f6f8;
  opacity: 0.5;
  border-radius: 3px;
  padding: 10px;
  font-size: 12px;
  cursor: default;
}

/* 动画样式 */
.css_animation {
  position: absolute;
  top: -1000px;
  z-index: 1000;
}

/* 地图加载提示样式 */
.map-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 1000;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

.loading-text {
  font-size: 18px;
  color: #333;
}

/* 从MapControls组件整合的样式 */
.map-controls {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1000;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  padding: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.control-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 10px;
}

.control-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 键盘控制提示样式 */
.keyboard-tips {
  margin-top: 12px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  user-select: none;
}

.tips-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-weight: bold;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  padding-bottom: 4px;
}

.close-icon {
  cursor: pointer;
  transition: color 0.2s;
}

.close-icon:hover {
  color: #ff4949;
}

.tips-content p {
  margin: 4px 0;
  display: flex;
  align-items: center;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

<style>
/* OpenLayers 提示样式 */
.ol-tooltip {
  position: relative;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
  color: white;
  padding: 4px 8px;
  opacity: 0.7;
  white-space: nowrap;
  font-size: 12px;
  cursor: default;
  user-select: none;
}

.ol-tooltip-measure {
  opacity: 1;
  font-weight: bold;
}

.ol-tooltip-static {
  background-color: #ffcc33;
  color: black;
  border: 1px solid white;
}

.ol-tooltip-measure:before,
.ol-tooltip-static:before {
  border-top: 6px solid rgba(0, 0, 0, 0.5);
  border-right: 6px solid transparent;
  border-left: 6px solid transparent;
  content: "";
  position: absolute;
  bottom: -6px;
  margin-left: -7px;
  left: 50%;
}

.ol-tooltip-static:before {
  border-top-color: #ffcc33;
}
</style> 